package com.coda.controller.user;

import com.coda.common.Result;
import com.coda.constant.JWTClaimsConstant;
import com.coda.constant.MessageConstant;
import com.coda.pojo.User;
import com.coda.pojo.vo.UserVo;
import com.coda.properties.JWTProperties;
import com.coda.service.UserService;
import com.coda.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;

@RestController
@RequestMapping("/user/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JWTProperties jwtProperties;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result<UserVo> login(@RequestBody User user) {
        //获取用户信息
        User userInfo = userService.login(user);

        //准备Claims（载荷）
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JWTClaimsConstant.ID,userInfo.getId());
        claims.put(JWTClaimsConstant.NAME,userInfo.getUsername());
        claims.put(JWTClaimsConstant.EMAIL,userInfo.getEmail());

        //创建jwt令牌
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );

        //设置返回的用户信息vo
        UserVo userVo = new UserVo(
                userInfo.getId(),
                userInfo.getUsername(),
                userInfo.getEmail(),
                token);
        return Result.success(userVo, MessageConstant.LOGIN_SUCCESS);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {

        int result = userService.register(user);
        if (result <= 0) {
            return Result.error(MessageConstant.REGISTER_FAILED);
        }
        return Result.success(MessageConstant.REGISTER_SUCCESS);
    }
}
